package com.zhilianbao.leyaogo.ui.fragment.me.myaccount;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bql.recyclerview.swipe.SwipeMenuAdapter;
import com.bql.recyclerview.swipe.SwipeMenuCreator;
import com.bql.roundview.RoundTextView;
import com.bql.utils.EventManager;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.app.LeYaoGoApplication;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.api.ShoppingCartApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.http.callback.LoadingViewCallback;
import com.zhilianbao.leyaogo.listener.OnAddToCartClickListener;
import com.zhilianbao.leyaogo.model.response.category.SkuEntity;
import com.zhilianbao.leyaogo.model.response.me.CouponCanUsedGoodsResponse;
import com.zhilianbao.leyaogo.model.response.shoppingcart.GoodsStock;
import com.zhilianbao.leyaogo.ui.activity.goodscategory.GoodsActivity;
import com.zhilianbao.leyaogo.ui.adapter.me.CouponCanUsedAdapter;
import com.zhilianbao.leyaogo.ui.fragment.base.SwipeRefreshAndLoadFragment;
import com.zhilianbao.leyaogo.ui.fragment.shoppingcart.ShoppingCartFragment;
import com.zhilianbao.leyaogo.utils.GoodsSpecPopUtils;
import com.zhilianbao.leyaogo.utils.ShopAnimationUtils;
import com.zhilianbao.leyaogo.utils.ShopNumUtils;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.view.decoration.ListLineDecoration;
import com.zhilianbao.leyaogo.view.widgets.MyRelativeLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by liu on 2016/10/29.
 * 查看适用商品
 */
public class SeeAvalibleGoodsFragment extends SwipeRefreshAndLoadFragment<CouponCanUsedGoodsResponse> implements OnAddToCartClickListener<CouponCanUsedGoodsResponse> {
    private static long mCouponsId;
    private static int mCouponLimitPrice;
    CouponCanUsedAdapter mCouponCanUsedAdapter;
    @BindView(R.id.iv_add_to_cart)
    ImageView ivAddToCart;
    @BindView(R.id.iv_cart_num)
    RoundTextView mIvCartNum;
    @BindView(R.id.rl_see_avalible_container)
    MyRelativeLayout mRlSeeAvalibleContainer;
    @BindView(R.id.coupon_title)
    TextView couponTitle;
    @BindView(R.id.rl_add_to_cart)
    RelativeLayout rlAddToCart;
    private int mGoodsSkuId;

    public static SeeAvalibleGoodsFragment getInstance(long couponsId, int couponLimitPrice) {
        mCouponsId = couponsId;
        mCouponLimitPrice = couponLimitPrice;
        SeeAvalibleGoodsFragment fragment = new SeeAvalibleGoodsFragment();
        return fragment;
    }

    @Override
    public void onRcvItemClick(RecyclerView.ViewHolder holder, int position) {
        //进入商品详情
        Bundle bundle = new Bundle();
        bundle.putInt(IntentConfig.BUNDLE_GOODS_ID, (int) mList.get(position).getGoodsId());
        Integer goodsSkuId = mList.get(position).getGoodsSkuId();
        if (goodsSkuId == null) {
            goodsSkuId = 0;
        }
        bundle.putInt(IntentConfig.BUNDLE_GOODS_SKU_ID, goodsSkuId);
        Utils.startActivity(mActivity, GoodsActivity.class, bundle);
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_see_avalible_goods;
    }

    @Override
    public SwipeMenuAdapter getAdapter() {
        return mCouponCanUsedAdapter;
    }

    @Override
    public RecyclerView.ItemDecoration getItemDecoration() {
        return new ListLineDecoration();
    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(mActivity);
    }

    @Override
    public SwipeMenuCreator getSwipeMenuCreator() {
        return null;
    }

    @Override
    public void onLeftSwipeMenuClick(int adapterPosition, int menuPosition) {

    }

    @Override
    public void onRightSwipeMenuClick(int adapterPosition, int menuPosition) {

    }


    @Override
    public void onRefresh() {
        loadDataList(1, true);
    }

    @Override
    public void loadDataList(int curPage, boolean isPullToRefresh) {
        mCurPage = curPage;
        AccountApi.getCanUsedGoodsList(mActivity, mCouponsId,   Utils.getUserLoginInfo().getUserId(), curPage, pageSize, new RefreshAndLoadCallback<List<CouponCanUsedGoodsResponse>>(isPullToRefresh) {
            @Override
            public void errorLeftOrEmptyBtnClick(View v) {
                loadDataList(1, false);
            }

            @Override
            public void onResultSuccess(List<CouponCanUsedGoodsResponse> couponCanUsedGoodsResponse, @Nullable Response response, LoadingViewCallback callback) {
                init(couponCanUsedGoodsResponse);
                handleRefreshAndLoadListData(mCurPage, callback, couponCanUsedGoodsResponse);
            }

        });
    }

    private void init(List<CouponCanUsedGoodsResponse> couponCanUsedGoodsResponse) {
        if (couponCanUsedGoodsResponse.size() != 0) {
            couponTitle.setVisibility(View.VISIBLE);
            rlAddToCart.setVisibility(View.VISIBLE);
        }
        if (mCouponLimitPrice == 0) {
            couponTitle.setText("以下商品可以使用该优惠券");
        } else {
            couponTitle.setText("以下商品订单满" + mCouponLimitPrice + "可以使用该优惠券");
        }
    }

    @Override
    public void onLoadMore() {
        loadDataList(mCurPage, true);
    }

    @Override
    protected void initToolbarHere() {
        initToolbar(getString(R.string.see_avalible_goods));
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        mCouponCanUsedAdapter = new CouponCanUsedAdapter(mActivity, mList);
        mCouponCanUsedAdapter.setOnAddCartClickListener(this);
        ShopNumUtils.show(mIvCartNum, LeYaoGoApplication.SHOPPING_CART_NUM);
    }

    public void onAddToCartClick(CouponCanUsedGoodsResponse couponCanUsedGoodsResponse, ImageView imageView) {
        if (Utils.isShowSpePop(couponCanUsedGoodsResponse.getGoodsType(), couponCanUsedGoodsResponse.getGoodsSkuId())) {//弹属性选择框
            showSkuPop(imageView, couponCanUsedGoodsResponse);
        } else {
            mGoodsSkuId = couponCanUsedGoodsResponse.getGoodsSkuId();
            addToShoppingCart(couponCanUsedGoodsResponse, imageView);
        }
    }

    private void addToShoppingCart(CouponCanUsedGoodsResponse couponCanUsedGoodsResponse, final ImageView imageView) {
        ShoppingCartApi.setShoppingCart(mActivity, Utils.getUserLoginInfo().getUserId(), couponCanUsedGoodsResponse.getGoodsId(), Utils.getSupplierId(), couponCanUsedGoodsResponse.getShopId(), mGoodsSkuId, 1, 0, new DialogCallback<GoodsStock>(mActivity) {
            @Override
            public void onSuccess(GoodsStock goodsStock, Call call, Response response) {
                ShopAnimationUtils.addToShoppingCart(mActivity, 0, imageView, ivAddToCart, mRlSeeAvalibleContainer, true, () -> {
                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ADD_TO_SHOPPING_CART));
                });
            }
        });
    }

    private void showSkuPop(ImageView imageView, CouponCanUsedGoodsResponse couponCanUsedGoodsResponse) {

        Utils.showSpecPop(mActivity, getView(), 1, couponCanUsedGoodsResponse.getGoodsPic(), couponCanUsedGoodsResponse.getGoodsSkuId(), couponCanUsedGoodsResponse.getSelectedSkuId(), couponCanUsedGoodsResponse.getSku(), couponCanUsedGoodsResponse.getSkuMap(), new GoodsSpecPopUtils.OnPopClickListener() {

            @Override
            public void onAddToCart(View v, int goodsSkuId) {
                mGoodsSkuId = goodsSkuId;
                addToShoppingCart(couponCanUsedGoodsResponse, imageView);
            }

            @Override
            public void onSpecSelect(SkuEntity skuEntity) {
                couponCanUsedGoodsResponse.setSelectedSkuId(skuEntity.getGoodsSkuId());
            }

        });

    }

    @OnClick({R.id.iv_add_to_cart})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_add_to_cart:
                start(ShoppingCartFragment.newInstance(true));
                break;
        }
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        switch (eventManager.getEventCode()) {
            case LeEventCode.MSG_CODE_REFRESH_SHOPPINGCART://从查看适用商品进入商品详情,购物车数据变化时通知收藏改变数据
            case LeEventCode.MSG_CODE_ADD_TO_SHOPPING_CART://添加购物车成功刷新购物车数量
            case LeEventCode.MSG_CODE_SET_SHOPPINGCART_SUCS://购物车数量设置成功
                ShopNumUtils.show(mIvCartNum, LeYaoGoApplication.SHOPPING_CART_NUM);
                break;
            case LeEventCode.MSG_CODE_FINISH_GOODS_ACTIVITY://从查看适用商品进入详情,进入购物车,点击去逛逛,finish掉优惠券页面
                mActivity.finish();
                break;
        }
    }
}
